<script setup lang="ts">
import type { FolderProps, OpenParamProps, OptionProps } from '@/types';

import {
  type ComponentInternalInstance,
  computed,
  getCurrentInstance,
  ref,
} from 'vue';

import { Icon } from '@/components/core/icon';

import { ArrowRight } from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import {
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElDialog,
  ElEmpty,
  ElMessage,
} from 'element-plus';

import { formatFileSize, formatIcon, splitChar } from '@/utils';

defineOptions({
  name: 'SelectByFileType',
});
const emits = defineEmits(['confirm']);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const baseUrl = proxy?.$config.baseUrl;
const visible = ref(false);
const loading = ref(false);
const list = ref<FolderProps[]>([]);
const openParam = ref<OpenParamProps>();
const currentPath = ref('');
const breadcrumb = computed(() => {
  if (currentPath.value === splitChar) return [];
  const paths = currentPath.value?.split(splitChar).filter(Boolean) || [];
  const result: OptionProps[] = [];
  let path = '';

  paths.forEach((item) => {
    if (item) {
      path += `${splitChar}${item}`;
      result.push({ name: item, path });
    }
  });

  return result;
});

const loadFolder = (path: string) => {
  currentPath.value = path;
  loading.value = true;
  try {
    const url = `${baseUrl}/folder/list?path=${path}&filter=${openParam.value?.exts?.join(',') || ''}`;
    fetch(url, {
      method: 'GET',
    })
      .then((response) => response.json())
      .then((res) => {
        const { code, data, msg } = res;
        if (code === 200 && data) {
          data.map((m: FolderProps) => {
            m.icon = formatIcon(m);
            m.parentPath = path;
            return m;
          });
          list.value = data as FolderProps[];
        } else {
          ElMessage.error(msg || '获取文件夹目录失败');
        }
      });
  } catch (error) {
    console.log(error);
    ElMessage.error('请求发生了错误，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const onItemDbClick = (item: FolderProps) => {
  const { ext, fullPath, type } = item;
  if (type === '2') {
    currentPath.value = fullPath || splitChar;
    loadFolder(fullPath);
  } else if (
    type === '1' &&
    (openParam.value?.exts?.includes(ext) || !openParam.value?.exts)
  ) {
    emits('confirm', item);
    visible.value = false;
  } else {
    ElMessage.error('该文件类型不在选择范围内');
  }
};
// 跳转到指定目录
const onGoto = (path: string) => {
  if (path) {
    loadFolder(path);
    currentPath.value = path;
  }
};
const open = (data?: OpenParamProps) => {
  visible.value = true;
  openParam.value = Object.assign({}, data);
  loadFolder(splitChar);
};
defineExpose({
  open,
});
</script>
<template>
  <ElDialog
    v-model="visible"
    :align-center="true"
    :center="true"
    :close-on-click-modal="false"
    :draggable="true"
    :footer="null"
    modal-class="wos-folder-common-dialog"
    width="640"
  >
    <template #header>
      <div class="dialog-header">
        {{ openParam?.title || '打开要移动的目标文件夹' }}
      </div>
    </template>
    <div class="dialog-body">
      <div class="dialog-body--breadcrumb">
        <ElBreadcrumb :separator-icon="ArrowRight">
          <ElBreadcrumbItem @click="onGoto(splitChar)">根目录</ElBreadcrumbItem>
          <ElBreadcrumbItem
            v-for="(item, index) in breadcrumb"
            :key="index"
            :title="item.name"
            @click="onGoto(item.path)"
          >
            {{ item.name }}
          </ElBreadcrumbItem>
        </ElBreadcrumb>
      </div>
      <div class="dialog-body--list small">
        <div class="layout-list">
          <table
            :class="{ 'h-full': list.length === 0 || loading }"
            class="hor-minimalist-b"
          >
            <colgroup>
              <col width="28" />
              <col width="auto" />
              <col width="160" />
              <col width="100" />
            </colgroup>
            <thead>
              <tr>
                <th scope="col"></th>
                <th class="sort" scope="col">
                  <div class="th">名称</div>
                </th>
                <th class="sort" scope="col">
                  <div class="th">修改时间</div>
                </th>
                <th class="sort" scope="col">
                  <div class="th">大小</div>
                </th>
              </tr>
            </thead>
            <tbody v-if="list.length === 0">
              <tr>
                <td colspan="4">
                  <ElEmpty description="此文件夹为空。" />
                </td>
              </tr>
            </tbody>
            <tbody v-else>
              <tr v-for="(item, index) in list" :key="index">
                <td>{{ index + 1 }}</td>
                <td>
                  <div class="title">
                    <Icon
                      :class="item.type === '2' ? 'folder' : 'file'"
                      :icon="item.icon"
                      class="mr-2"
                    />
                    <div class="name" @dblclick="onItemDbClick(item)">
                      {{ item.name }}
                    </div>
                  </div>
                </td>
                <td>
                  {{ dayjs(item.mtime).format('YYYY-MM-DD HH:mm:ss') }}
                </td>
                <td>
                  {{ item.type === '2' ? '' : formatFileSize(item.size) }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </ElDialog>
</template>

<style lang="scss">
@import url('./index.scss');
</style>
